"""
通知管理相关的 API 路由
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Optional

from api.deps import get_db, get_current_doctor
from crud.notification import crud_notification
from schemas.notification import (
    NotificationCreate,
    NotificationUpdate,
    NotificationResponse
)
from models.doctor import Doctor
from utils.response import success_response, error_response

router = APIRouter()


@router.post("", status_code=201)
async def create_notification(
    notification_in: NotificationCreate,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_doctor)
):
    """
    创建通知
    
    **请求参数：**
    - title: 通知标题
    - desc: 通知描述
    - date: 通知日期
    """
    try:
        notification = await crud_notification.create(db, obj_in=notification_in)
        
        return {
            "message": "通知创建成功",
            "id": str(notification.id),
            "code": 0
        }
    except Exception as e:
        return error_response(f"创建失败: {str(e)}")


@router.get("")
async def get_notifications(
    page: int = Query(1, ge=1, description="页码"),
    per_page: int = Query(10, ge=1, le=100, description="每页数量"),
    is_read: Optional[str] = Query(None, description="是否已读（true/false）"),
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_doctor)
):
    """
    获取通知列表（分页）
    
    **请求参数：**
    - page: 页码，默认1
    - per_page: 每页数量，默认10
    - is_read: 是否已读（可选，true/false）
    """
    try:
        # 处理 is_read 参数
        is_read_bool = None
        if is_read is not None:
            is_read_bool = is_read.lower() == 'true'
        
        # 获取总数
        total = await crud_notification.count_all(db, is_read=is_read_bool)
        
        # 计算总页数
        total_pages = (total + per_page - 1) // per_page
        
        # 获取通知列表
        notifications = await crud_notification.get_list(
            db,
            page=page,
            per_page=per_page,
            is_read=is_read_bool
        )
        
        # 转换为 Flask 格式的响应
        notification_list = []
        for notification in notifications:
            notification_response = NotificationResponse.model_validate(notification)
            notification_list.append(notification_response.to_flask_format())
        
        return {
            "message": "获取通知列表成功",
            "data": {
                "notifications": notification_list,
                "total": total,
                "totalPages": total_pages,
                "currentPage": page,
                "perPage": per_page
            },
            "code": 0
        }
    except Exception as e:
        return error_response(f"获取通知列表失败: {str(e)}")


@router.get("/all")
async def get_all_notifications(
    is_read: Optional[str] = Query(None, description="是否已读（true/false）"),
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_doctor)
):
    """
    获取所有通知记录（不分页）
    
    **请求参数：**
    - is_read: 是否已读（可选，true/false）
    """
    try:
        # 处理 is_read 参数
        is_read_bool = None
        if is_read is not None:
            is_read_bool = is_read.lower() == 'true'
        
        # 获取所有通知
        notifications = await crud_notification.get_all(
            db,
            is_read=is_read_bool
        )
        
        # 转换为 Flask 格式的响应
        notification_list = []
        for notification in notifications:
            notification_response = NotificationResponse.model_validate(notification)
            notification_list.append(notification_response.to_flask_format())
        
        return {
            "message": "获取通知列表成功",
            "data": notification_list,
            "code": 0
        }
    except Exception as e:
        return error_response(f"获取通知列表失败: {str(e)}")


@router.put("/{notification_id}")
async def update_notification(
    notification_id: int,
    notification_update: NotificationUpdate,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_doctor)
):
    """
    更新通知
    
    **请求参数：**
    - title: 通知标题（可选）
    - desc: 通知描述（可选）
    - date: 通知日期（可选）
    - is_read: 是否已读（可选）
    """
    try:
        # 检查通知是否存在
        notification = await crud_notification.get(db, id=notification_id)
        if not notification:
            return error_response("通知不存在", status_code=404)
        
        # 更新通知
        updated_notification = await crud_notification.update(
            db,
            db_obj=notification,
            obj_in=notification_update
        )
        
        return {
            "message": "通知更新成功",
            "code": 0
        }
    except ValueError:
        return error_response("无效的通知ID", status_code=400)
    except Exception as e:
        return error_response(f"更新失败: {str(e)}")


@router.delete("/{notification_id}")
async def delete_notification(
    notification_id: int,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_doctor)
):
    """
    删除通知（软删除）
    """
    try:
        # 软删除通知
        success = await crud_notification.soft_delete(
            db,
            notification_id=notification_id
        )
        
        if not success:
            return error_response("通知不存在", status_code=404)
        
        return {
            "message": "通知删除成功",
            "code": 0
        }
    except ValueError:
        return error_response("无效的通知ID", status_code=400)
    except Exception as e:
        return error_response(f"删除失败: {str(e)}")

